# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_util.py
# @Time      :2022/5/28 13:23
# @Author    :张志坤

import jwt
from datetime import datetime, timedelta
from flask import current_app
from flask_restful import current_app


# 生成token
def generate_jwt(payload, expiry, secret=None):
    """
    生成token
    :param payload: 'id': 2, 'username': 'admin123'
    :param expiry:   过期时间
    :param secret:   盐
    :return: token
    """
    payload['exp'] = expiry
    print("payload是哈>>>>>>", payload)
    # 若盐为空
    if not secret:
        # 获取盐
        secret = current_app.config.get('SECRET_KEY')
        print("我是盐啊>>>>", secret)
    # 通过jwt的encode方法传入  payload,盐,加密方法  生成token
    token = "JWT " + jwt.encode(payload, secret, algorithm="HS256")
    return token


def verify_jwt(token, secret=None):
    """
    校验jwt token
    :param token:
    :param secret:
    :return: payload
    """
    # 若盐为空
    if not secret:
        # 获取盐
        secret = current_app.config['SECRET_KEY']
    try:
        # 使用jwt的decode进行解码  传入参数 token  secret  加密方式
        payload = jwt.decode(token, secret, algorithms=["HS256"])
    except Exception as e:
        print("解码token报错", e)
        payload = None
    print("解码token的payload", payload)
    return payload


def _generate_token(payload, is_refresh=True):
    """
    :param payload:
    :return:
    """
    secret = current_app.config['SECRET_KEY']
    # 设置有效期  第一个默认生成2小时的有效期
    expiry = datetime.utcnow() + timedelta(hours=2)
    token = generate_jwt(payload, expiry, secret)
    # is_refresh作为刷新token 的信号
    if is_refresh:
        # 刷新生成的token,有效期15天
        expiry = datetime.utcnow() + timedelta(days=15)
        # 给payload添加刷新token的表识
        payload.update({"is_refresh": True})
        print('刷新token 的payload```', payload)
        # 生成刷新的token
        refresh_token = generate_jwt(payload, expiry, secret)
    else:
        refresh_token = None
    # payload = verify_jwt(refresh_token[4:])
    # print("新生成的token解码",payload)

    return token, refresh_token
